﻿using UnityEngine;
using System.Collections;
using System.Net;
using System;
using System.Runtime.InteropServices;
using System.IO;
using LitJson;
using UnityEngine.UI;
using System.Linq;
using System.Collections.Generic;
using UnityEngine.SceneManagement;
using GameCore;
using com.guojin.mj.net.message.login;
using System.Threading;
using System.Text;
using ImageVideoContactPicker;

public class LoginAndShare : MonoBehaviour
{
    public static string title1 = "牛牛吧[点击进入下载]";
    public static string content = "玩家：" + GameData.GetInstance().userName + " ID：" + GameData.GetInstance().userID + " 邀请您加入[牛牛吧]，点击此消息进入下载页面！";

    public string content1 = "玩家：" + GameData.GetInstance().userName + " 在[牛牛吧]开了 "  +GameRoomModel.GetInstance().RoomExistenceTime + " 分钟，快来一起玩吧. 输入房间号进入游戏.";

    public static bool isMicrophoneOk;
    public string returnTitle(string name, string id)
    {
        string content = "玩家：" + name + " ID：" + id + " 邀请您加入[牛牛吧]，点击此消息进入下载页面！";
        return content;
    }

    public string returnTitle1(string roomid)
    {
        string title1;
        title1 = "牛牛吧- ：房号[ " + roomid + " ]";
        return title1;
    }

    public string returnContent(string name, string maxChapter)
    {
        string content1 = "玩家：" + name + " 在[牛牛吧]开了 " + GameRoomModel.GetInstance().RoomExistenceTime + " 分钟，快来一起玩吧. 输入房间号进入游戏.";
        return content1;
    }

    //分享内容
    public string returnContentRoom()
    {
        return "玩家：" + GameData.GetInstance().userName + " 在[牛牛吧]开了 " + GameRoomModel.GetInstance().RoomExistenceTime + " 分钟，快来一起玩吧. 输入房间号进入游戏.";
    }

    private static LoginAndShare _Controller = null;

    public static LoginAndShare Controller
    {
        get
        {
            if (_Controller == null)
            {
                _Controller = GameObject.Find("StaticSource").GetComponent<LoginAndShare>();
            }
            return _Controller;
        }
    }
    void OnEnable()
    {
        PickerEventListener.onImageSelect += OnImageSelect;
        PickerEventListener.onImageLoad += OnImageLoad;
        PickerEventListener.onVideoSelect += OnVideoSelect;
        PickerEventListener.onContactSelect += OnContactSelect;
        PickerEventListener.onError += OnError;
        PickerEventListener.onCancel += OnCancel;
    }

    void OnDisable()
    {
        PickerEventListener.onImageSelect -= OnImageSelect;
        PickerEventListener.onImageLoad -= OnImageLoad;
        PickerEventListener.onVideoSelect -= OnVideoSelect;
        PickerEventListener.onContactSelect -= OnContactSelect;
        PickerEventListener.onError -= OnError;
        PickerEventListener.onCancel -= OnCancel;
    }
    void OnVideoSelect(string vidPath)
    {
        Debug.Log("Video Location : " + vidPath);

    }

    void OnContactSelect(string name, List<string> numbers, List<string> emails)
    {
        Debug.Log("Name : " + name);

    }
    void OnImageSelect(string imgPath)
    {
        Debug.Log("Image Location : " + imgPath);

    }
    void OnImageLoad(string imgPath, Texture2D tex)
    {
        Debug.Log("Image Location : " + imgPath);
        Mytexture = GameObject.Find("Headimages").GetComponent<RawImage>();

        //ImageStart(path1);
        Mytexture.texture = tex;
        Texture2D tex2d = Mytexture.texture as Texture2D;
        Debug.Log("转换tex2d完成");
        tex2d = ScaleTexture(tex2d, 300, 300);
        Debug.Log("缩放完成");
        byte[] bytes = tex2d.EncodeToPNG();
        // Debug.Log(bytes);
        ImageStart(bytes);
    }
    void OnError(string errorMsg)
    {
        Debug.Log("Error : " + errorMsg);

    }
   void OnCancel()
    {
        Debug.Log("Cancel by user");
    }


    //调用JAR包的方法
    public void callAndroidJava(string methodName, params object[] args)
    {
#if UNITY_ANDROID
        using (AndroidJavaClass jc = new AndroidJavaClass("com.unity3d.player.UnityPlayer"))
        using (AndroidJavaObject jo = jc.GetStatic<AndroidJavaObject>("currentActivity"))
        {
            jo.Call(methodName, args);
            Debug.LogError(methodName + " Called");
        }
#endif
    }

    //分享截图
    public void sharePng()
    {
#if WX_SDK
        StartCoroutine(GetCapture());
#else
        StartCoroutine(GetCapture());
#endif
    }

    IEnumerator GetCapture()
    {

        yield return new WaitForEndOfFrame();

        int width = Screen.width;

        int height = Screen.height;

        Texture2D tex = new Texture2D(width, height, TextureFormat.RGB24, false);

        tex.ReadPixels(new Rect(0, 0, width, height), 0, 0, true);

        byte[] imagebytes = tex.EncodeToPNG();//转化为png图  
        tex.Compress(false);//对屏幕缓存进行压缩  
        //File.WriteAllBytes(Application.dataPath + "/123.txt", imagebytes);
        File.WriteAllBytes(Application.persistentDataPath + "/screencapture.png", imagebytes);//存储png图 
#if UNITY_ANDROID
        this.callAndroidJava("saveCurrentImage",
            new object[]
                        {
                                Application.persistentDataPath + "/screencapture.png",0,0
                        });
#elif UNITY_IPHONE
        SharePNG();
#endif
    }

    public void GoToProcessView()
    {
        callAndroidJava("GoToProcessView");
    }

    public void GetPlaceInfo()
    {
        callAndroidJava("SendPlaceToUnity");
    }

    //IOS获取定位信息，游戏启动时调用
    public void GetPlayerPlaceIOS(string place)
    {
        Debug.Log("unity获取的地理位置" + place);
        List<string> p = place.Split('_').ToList();
        GameData.GetInstance().longitude = p[0];
        GameData.GetInstance().latitude = p[1];
    }

    //安卓获取定位信息，游戏启动时jar包中调用
    public void GetPlayerPlace(string place)
    {
        Debug.Log("unity获取的地理位置" + place);
        List<string> p = place.Split('_').ToList();
        GameData.GetInstance().place = p[0];
        GameData.GetInstance().longitude = p[1];
        GameData.GetInstance().latitude = p[2];
    }

    //实时定位返回
    public void GetPlayerPlace2(string str)
    {
        Debug.Log("unity获取的实时地理位置" + str);
        List<string> p = str.Split('_').ToList();
        GameData.GetInstance().place = p[0];
        GameData.GetInstance().longitude = p[1];
        GameData.GetInstance().latitude = p[2];

        //向服务器发送经纬度
       // MessageManager.GetInstance().SendMsg135(0, p[1], p[2]);
    }


    public void GetCapture_version2(int shareType)
    {
        this.callAndroidJava("saveCurrentImage",
                        new object[]
                        {
                                Application.persistentDataPath + "/sharecapture.png",shareType,1
                        });
    }

    //跳转到新版本网页
    public void GetNewVersionBtnClick()
    {
#if UNITY_ANDROID
        this.callAndroidJava("OpenWebView", URLConst.ShareUrl);
#elif UNITY_IPHONE
        openDownloadUrl(URLConst.ShareUrl);
#endif
    }

    //打开网站方法
    public void GetAgency(string url)
    {
#if UNITY_ANDROID
        this.callAndroidJava("OpenWebView", url);
#elif UNITY_IPHONE
        GetAgentios(url);
#endif
    }

    //打电话
    public void CallPhone()
    {
#if UNITY_ANDROID
        this.callAndroidJava("CallTelBtnClick");
#elif UNITY_IPHONE
        CallPhoneios(NumConst.IosTelNum);
#endif
    }

    //显示安卓原生提示
    public void ShowAndroidMsg(string msg)
    {
        this.callAndroidJava("shoumsg", msg);
    }

    public void SharePngIos()
    {
#if UNITY_IPHONE
        ShareQRPng();
#endif
    }


#if UNITY_IPHONE
    [DllImport("__Internal")]
    private static extern void OnClickSharedios(string roomIDTex, string sec,string url);//unity 调用ios的分享方法传入了两个参数 roomIDTex 和描述
#endif
#if UNITY_IPHONE
    [DllImport("__Internal")]
    private static extern void CallPhoneios(string phonenum);//unity 调用ios的打电话方法
#endif
#if UNITY_IPHONE
    [DllImport("__Internal")]
    private static extern void OnClickWXLoginios();//unity 调用ios的登录方法
#endif
#if UNITY_IPHONE
    [DllImport("__Internal")]
    private static extern void GetAgentios(string dailiurl);//unity 调用ios的登录方法，需要回调OnWXloginCallBack 带参数code
#endif
#if UNITY_IPHONE
    [DllImport("__Internal")]
    private static extern void SharePNG();//unity 调用ios的登录方法，分享PNG图片
#endif
#if UNITY_IPHONE
    [DllImport("__Internal")]
    private static extern void openDownloadUrl(string downloadUrl);//打开下载页面

    [DllImport("__Internal")]
    private static extern bool ShareQRPng();
#endif
#if UNITY_IPHONE
    [DllImport("__Internal")]
    private static extern void IOSOnWXPay(string appid,string noncestr,string packageid,string partnerid,string prepayid,string timestamp,string sign);
#endif
#if UNITY_IPHONE
    [DllImport("__Internal")]
    private static extern void IOSOnZFBPay(string sign);
#endif

    public void CallIosZfb(string sign)
    {
#if UNITY_IPHONE
        IOSOnZFBPay(sign);
#endif
    }


    //接收服务器返回支付信息，吊起微信
    public void OnRecePayRet(string appid, string noncestr, string packageid, string partnerid, string prepayid, string timestamp, string sign)
    {
        Debug.Log(appid);
        Debug.Log(noncestr);
        Debug.Log(packageid);
        Debug.Log(partnerid);
        Debug.Log(prepayid);
        Debug.Log(timestamp);
        Debug.Log(sign);
#if UNITY_ANDROID
        this.callAndroidJava("genPayReq", appid, noncestr, packageid, partnerid, prepayid, timestamp, sign);
#elif UNITY_IPHONE
        IOSOnWXPay(appid, noncestr, packageid, partnerid, prepayid, timestamp, sign);
#endif
    }

    //复制到android和ios剪切板
    public void CopyTextToClipboard(string str)
    {
#if UNITY_ANDROID
        this.callAndroidJava("copyTextToClipboard", str);
#elif UNITY_IPHONE
        //TODO
#endif
    }

    //分享送钻石
    /// <summary>
    /// 分享按钮事件
    /// </summary>
    public void OnClickShared(int shareType, string url)
    {
        content = returnTitle(GameData.GetInstance().userName, GameData.GetInstance().userID.ToString());
#if UNITY_ANDROID
        Debug.Log("---c# onClickShared ---");
        AndroidJavaClass jc = new AndroidJavaClass("com.unity3d.player.UnityPlayer");
        AndroidJavaObject jo = jc.GetStatic<AndroidJavaObject>("currentActivity");
        jo.Call("OnWeChatShared", "牛牛吧[点击进入下载]", content, shareType);
#elif UNITY_IPHONE
        OnClickSharedios( "牛牛吧[点击进入下载]", content,url);
#endif
    }


    //邀请玩家
    public void OnClickShareInfo(string url)
    {
        title1 = returnTitle1(GameRoomModel.GetInstance().RoomID);
        content1 = returnContentRoom();
#if UNITY_ANDROID
        AndroidJavaClass jc = new AndroidJavaClass("com.unity3d.player.UnityPlayer");
        AndroidJavaObject jo = jc.GetStatic<AndroidJavaObject>("currentActivity");
        jo.Call("OnWeChatShared", title1, content1, GameRoomModel.GetInstance().RoomID, 0);
#elif UNITY_IPHONE
        OnClickSharedios(title1, content1,url+ "?roomNo=" + GameRoomModel.GetInstance().RoomID);
#endif
    }

    //代开房分享
    public void ReplaceCreatRoomShare(string gameType, string roomId, string chapterNum, string topNum, string url)
    {
        title1 = returnTitle1(roomId);
        content1 = gameType + ", " + chapterNum + "局," + topNum + "封顶，" + "赶快来!";
#if UNITY_ANDROID
        AndroidJavaClass jc = new AndroidJavaClass("com.unity3d.player.UnityPlayer");
        AndroidJavaObject jo = jc.GetStatic<AndroidJavaObject>("currentActivity");
        jo.Call("OnWeChatShared", title1, content1, roomId, 0, url);
#elif UNITY_IPHONE
        OnClickSharedios(title1, content1,url+ "?roomNo=" + GameRoomModel.GetInstance().RoomID);
#endif
    }


    public void OnClickShareInfoForAndroid(int shareType, string url)
    {
        title1 = returnTitle1(GameRoomModel.GetInstance().RoomID);
        Debug.Log("GameRoomID>>" + GameRoomModel.GetInstance().RoomID);
       // content1 = returnContent(GameData.GetInstance().userName, GameRoomModel.GetInstance().MaxChapter.ToString());
        AndroidJavaClass jc = new AndroidJavaClass("com.unity3d.player.UnityPlayer");
        AndroidJavaObject jo = jc.GetStatic<AndroidJavaObject>("currentActivity");
        jo.Call("OnWeChatShared", title1, content1, GameRoomModel.GetInstance().RoomID, shareType, url);
    }


    //ios 调用InviteFriendsBtn 的OnSharedCallBack 带 string 参数
    public void OnSharedCallBack(string result)
    {
        if (result.Equals("succeed"))
        {
            Debug.Log("--- c# onSharedCallBack");
            MessageManager.GetInstance().SendMsg732();
        }
    }


    /// <summary>
    ///微信登录按钮事件
    /// </summary>
    public void OnClickWXLogin()
    {
        Debug.Log("调用jar包的微信登录方法");
#if UNITY_ANDROID
        AndroidJavaClass jc = new AndroidJavaClass("com.unity3d.player.UnityPlayer");
        AndroidJavaObject jo = jc.GetStatic<AndroidJavaObject>("currentActivity");
        jo.Call("OnClickWXLogin");
        Debug.Log(" jo.Call(OnClickWXLogin)");
#elif UNITY_IPHONE
        OnClickWXLoginios();
#endif
    }

    /// <summary>
    /// 登录回调
    /// </summary>
    /// <param name="code"></param>
    //ios 调用WEIXINLogin 的OnWXloginCallBack 带 string 参数
    void OnWXloginCallBack(string code)
    {
        Debug.Log("微信登录返回" + code);
        wxCode = code;
        //这里需要开启已给新线程来处理微信登录，因为如果主线程发送http请求会造成等待返回消息时间卡顿
        Thread thread1 = new Thread(new ThreadStart(CallWX));
        thread1.Start();
        Debug.Log("开始处理微信登录返回");
    }

    //开启第二线程吊起微信的方法
    void CallWX()
    {
        string url = URLConst.WXAppLoginCallBackUrl;
        JsonData data = new JsonData();
        data["code"] = wxCode;
        string content = HttpPostData(url, "data=" + data.ToJson());
        JsonData jd = JsonMapper.ToObject(content);
        if (jd["status"].ToJson() == "-1")
        {
            Debug.Log("登录失败");//todo:sunfei 微信登录回调失败处理
        }
        else
        {
            wxCodeFromSever = jd["data"].ToJson();
            hasCode = true;
        }
    }

    //等待登录回掉信息的返回
    public string HttpPostData(string url, string param)
    {
        var result = string.Empty;
        //注意提交的编码 这边是需要改变的 这边默认的是Default：系统当前编码
        byte[] postData = System.Text.Encoding.UTF8.GetBytes(param);
        // 设置提交的相关参数 
        HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
        System.Text.Encoding myEncoding = System.Text.Encoding.UTF8;
        request.Method = "POST";
        request.KeepAlive = false;
        request.AllowAutoRedirect = true;
        request.ContentType = "application/x-www-form-urlencoded";
        request.UserAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 2.0.50727; .NET CLR  3.0.04506.648; .NET CLR 3.5.21022; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729)";
        request.ContentLength = postData.Length;

        // 提交请求数据 
        Stream outputStream = request.GetRequestStream();
        outputStream.Write(postData, 0, postData.Length);
        outputStream.Close();
        HttpWebResponse response;
        Stream responseStream;
        StreamReader reader;
        string srcString;
        response = request.GetResponse() as HttpWebResponse;
        responseStream = response.GetResponseStream();
        reader = new StreamReader(responseStream, System.Text.Encoding.GetEncoding("UTF-8"));
        srcString = reader.ReadToEnd();
        result = srcString;   //返回值赋值 通过返回值判断是否登录成功
        reader.Close();
        return result;
    }

    bool hasCode = false;
    public string wxCode;
    public string wxCodeFromSever;
    private void Update()
    {
        if (hasCode == true)
        {
            hasCode = false;
            GameObject obj = GameObject.Find("Canvas/addNode/LoginPage(Clone)");
            if (obj)
            {
                obj.GetComponent<LoginPage>().wxLoginBtn.enabled = false;
                StartCoroutine(HandleWxLogin());
            }

            string longitude = GameData.GetInstance().longitude;
            string latitude = GameData.GetInstance().latitude;
            Debug.Log("longitude>>" + longitude + "  latitude>>" + latitude);

            MessageManager.GetInstance().SendMsg78("WEIXIN", null, wxCodeFromSever, longitude, latitude);
        }
    }

    public IEnumerator HandleWxLogin()
    {
        yield return new WaitForSeconds(1.5f);
        GameObject obj = GameObject.Find("Canvas/addNode/LoginPage(Clone)");
        if (obj)
        {
            obj.GetComponent<LoginPage>().wxLoginBtn.enabled = true;
        }
    }


    void OnApplicationPause(bool isPause)
    {
        if (!isPause && SceneManager.GetActiveScene().name == "SHGameHall")
        {
            if (GameObject.Find("GameRoomPage(Clone)"))
            {
                WorldTime.Instance.ReSetHeartBeat();
                WorldTime.Instance.BreakLine();
            }
        }

        if (isPause && SceneManager.GetActiveScene().name == "SHGameHall")
        {
            if (GameObject.Find("GameRoomPage(Clone)"))
            {
                SocketMgr.GetInstance().CloseSocket();
                SocketMessageQueue.open = true;
            }
        }


#if UNITY_ANDROID && !UNITY_EDITOR
        if (!isPause && SceneManager.GetActiveScene().name == "SHGameHall")
        {
            Debug.Log("OnApplicationPause>>GetRoomIDFromAD>>  0");
            StartCoroutine(GetRoomIDFromAD());
            Debug.Log("OnApplicationPause>>GetRoomIDFromAD>>  1");
        }
        if (!isPause && SceneManager.GetActiveScene().name == "Horizontal")
        {
            CheckMicrophone();
        }
        if (!isPause && SceneManager.GetActiveScene().name == "GameHall")
        {
            GameObject obj = GameObject.Find("Canvas/addNode/WaitStartGame(Clone)");
            if (obj)
            {
                callAndroidJava("GetPlayerPlace2");
            }
        }
#elif UNITY_IPHONE
#endif
    }

    IEnumerator GetRoomIDFromAD()
    {
        yield return new WaitForSeconds(1f);
        Debug.Log("OnApplicationPause>>GetRoomIDFromAD>>  2");
        this.callAndroidJava("GetRoomIDFromAD");
    }

    public void CheckMicrophone()
    {
        this.callAndroidJava("HasRecordPermission");
    }

    public void CheckMicrophoneCallBack(string req)
    {
        if (req.Equals("true"))
        {
            isMicrophoneOk = true;
        }
        else
        {
            isMicrophoneOk = false;
        }
    }

    public void GetRoomNoFromAD()
    {
        callAndroidJava("GotoRoom");
    }

    //jar包唤醒应用调用的方法
    public void GotoRoom(string RoomID)
    {
        Debug.Log("这是从H5--AD 获得的RoomID》》>00>" + RoomID);
        if (RoomID != null && RoomID != "")
        {
            //如果是大厅场景， 大厅界面走加入房间，战斗界面不做操作
            if (SceneManager.GetActiveScene().name.Equals("SHGameHall"))
            {
                if (GameObject.Find("GameRoomPage(Clone)"))
                {
                    Debug.Log("从H5过渡到战斗场景不做操作！");
                }
                else
                {
                    UIState_SHGameHallState.ifComeFromH5 = true;

                    MessageManager.GetInstance().SendMsg126();
                }
            }
            else
            {
                //如果是登录场景,  对房间号赋值
                UIState_SHGameHallState.H5RoomId = RoomID;
                UIState_SHGameHallState.ifComeFromH5 = true;
                Debug.Log("这是从H5--AD 获得的RoomID》》11>>" + RoomID);
            }
        }
        else
        {
            Debug.Log("H5返回的房间号有问题：" + RoomID);
        }
    }

    public AudioClip ac;
    //播放按键音
    public void BtnVoice()
    {
        if (PlayerPrefs.GetFloat("AudioSet", 1) >= 0.1f)
        {
            AudioSource.PlayClipAtPoint(ac, Vector3.zero);
        }
    }
    RawImage Mytexture;
    /// <summary>
    /// types==0 打开相册   1打开相机
    /// </summary>
    /// <param name="types"></param>
    public void OpenPhoto(int types)
    {
        if (types==0)

        {    //调用我们制作的Android插件打开手机相册    
#if UNITY_ANDROID
            //AndroidJavaClass jc = new AndroidJavaClass("com.unity3d.player.UnityPlayer");
            //AndroidJavaObject jo = jc.GetStatic<AndroidJavaObject>("currentActivity");
            //jo.Call("TakePhoto", "takeSave",Application.persistentDataPath);
            AndroidPicker.BrowseImage(true);
#elif UNITY_IPHONE
            IOSPicker.BrowseImage(true);
#endif
        }
        if (types == 1)
        {    //调用我们制作的Android插件打开手机摄像机 

#if UNITY_ANDROID
            //AndroidJavaClass jc = new AndroidJavaClass("com.unity3d.player.UnityPlayer");
            //AndroidJavaObject jo = jc.GetStatic<AndroidJavaObject>("currentActivity");
            //jo.Call("TakePhoto", "takePhoto",Application.persistentDataPath);
            AndroidPicker.BrowseImage(true);
#elif UNITY_IPHONE
            IOSPicker.BrowseImage(true);
#endif
        }
    }

    public void  messgae(string str) {
        //在Android插件中通知Unity开始去指定路径中找图片资源  
        Debug.Log("messgae==>" + str);
        StartCoroutine(LoadTexture(str)); }

    IEnumerator LoadTexture(string name)  {
        //注解1 
        string path  ="file:///" + Application.persistentDataPath +"/" + name;
        string path1= Application.persistentDataPath + "/" + name;

        Debug.Log("LoadTexture path==>" + path);
        WWW www = new WWW(path);
        while (!www.isDone) {  }
        Mytexture = GameObject.Find("Headimages").GetComponent<RawImage>();
        yield return www;
        //ImageStart(path1);
        Mytexture.texture = www.texture;

        Debug.Log("开始处理");
        //Texture2D tex2d = TextureToTexture2D(Mytexture.texture);
        Texture2D tex2d = Mytexture.texture as Texture2D;
        Debug.Log("转换tex2d完成");
        tex2d = ScaleTexture(tex2d, 300, 300);
        Debug.Log("缩放完成");
        byte[] bytes = tex2d.EncodeToPNG();
       // Debug.Log(bytes);
        ImageStart(bytes);
    }

    //private Texture2D TextureToTexture2D(Texture texture)
    //{
      
    //    UnityEditor.TextureImporter ti = (UnityEditor.TextureImporter)UnityEditor.TextureImporter.GetAtPath(UnityEditor.AssetDatabase.GetAssetPath(texture2d));
    //    //图片Read/Write Enable的开关
    //    ti.isReadable = true;
    //    UnityEditor.AssetDatabase.ImportAsset(UnityEditor.AssetDatabase.GetAssetPath(texture2d));
    //    return texture2d;
    //}
    
    private Texture2D ScaleTexture(Texture2D source, int targetWidth, int targetHeight)
    {
        Texture2D result = new Texture2D(targetWidth, targetHeight, source.format, false);
        for (int i = 0; i < result.height ; i++)
        {
            for (int j = 0; j < result.width; j++)
            {
                Color newColor = source.GetPixelBilinear((float) j/(float) result.width, (float) i/(float) result.height);
                result.SetPixel(j, i, newColor);
            }
        }
        result.Apply();
        return result;
    }

    void ImageStart(byte[] bytes)
    {

        string base64 = Convert.ToBase64String(bytes);
        GameObject temp = GameObject.Find("Setnumber(Clone)");
        GameObject temp1=GameObject.Find("LiuYan(Clone)"); 
        GameObject temp2 = GameObject.Find("MyClub(Clone)");
        GameObject temp3 = GameObject.Find("MyLegends(Clone)");
        GameObject temp4 = GameObject.Find("ChangeInfo(Clone)");
        if (temp)
        {
            temp.GetComponent<Setnumber>().headsBase64 = base64;           
        }
        else if(temp1) {
                temp1.GetComponent<LiuYanPanel>().picture = base64;          
            //else
            //{
            //    SaveDate.GetInstance().image64 = base64;
            //}
        }
        else if (temp3)
        {
            temp3.GetComponent<MyLegend>().himag = base64;          
        }
        else if (temp2)
        {
            temp2.GetComponent<MyClubbPanel>().HImage = base64;
        }
        else if (temp4)
        {
            temp2.GetComponent<ChangeInfo>().headsBase64 = base64;
        }
    }
    void IosImageStart(string pngstr)
    {
        string base64 = pngstr;
        GameObject temp = GameObject.Find("Setnumber");
        GameObject temp1 = GameObject.Find("LiuYan(Clone)");
        GameObject temp2 = GameObject.Find("MyClub(Clone)");
        GameObject temp3 = GameObject.Find("MyLegends(Clone)");
        GameObject temp4 = GameObject.Find("ChangeInfo(Clone)");

        if (temp)
        {
            temp.GetComponent<Setnumber>().headsBase64 = base64;
        }
        else if (temp4)
        {
            temp2.GetComponent<ChangeInfo>().headsBase64 = base64;
        }
        else if (temp1)
        {
            temp1.GetComponent<LiuYanPanel>().picture = base64;
            //else
            //{
            //    SaveDate.GetInstance().image64 = base64;
            //}
        }
        else if (temp3)
        {
            temp3.GetComponent<MyLegend>().himag = base64;
        }
        else if (temp2)
        {
            temp2.GetComponent<MyClubbPanel>().HImage = base64;
        }
    }
    /// 图片转为byte[]    
    private byte[] ImageToBytes(string imageFileName)
    {
        return File.ReadAllBytes(imageFileName);
    }
    /// 图片转为Base64  
    private string ImageToBase64(string imageFileName)
    {
        byte[] buffers = ImageToBytes(imageFileName);
        return Convert.ToBase64String(buffers);
    }


    public void backLoginPage()
    {
        StartCoroutine("WaitSocketClose");
    }
     IEnumerator WaitSocketClose()
    {
        yield return new WaitForSeconds(0.05f);
        if (!SocketMgr.GetInstance().isNetOpen)
        {
            GameObject addnode = GameObject.Find("addNode");
            DestroyChildren(addnode.transform);
            //弹出登陆界面
            UIManager.ChangeUI(UIManager.PageState.LoginPage, (GameObject obj) =>
            {
                obj.GetComponent<LoginPage>().InformationSetting();
            });
        }
        else
        {
            StartCoroutine("WaitSocketClose");
        }
    }
    void DestroyChildren(Transform t)
    {
        bool isPlaying = Application.isPlaying;

        while (t.childCount != 0)
        {
            Transform child = t.GetChild(0);

            if (isPlaying)
            {
                child.parent = null;
                UnityEngine.Object.Destroy(child.gameObject);
            }
            else UnityEngine.Object.DestroyImmediate(child.gameObject);


        }
    }
#if UNITY_IPHONE

    [DllImport("__Internal")]
    private static extern void _iosOpenPhotoLibrary();
    [DllImport("__Internal")]
    private static extern void _iosOpenPhotoAlbums();
    [DllImport("__Internal")]
    private static extern void _iosOpenCamera();
    [DllImport("__Internal")]
    private static extern void _iosOpenPhotoLibrary_allowsEditing();
    [DllImport("__Internal")]
    private static extern void _iosOpenPhotoAlbums_allowsEditing();
    [DllImport("__Internal")]
    private static extern void _iosOpenCamera_allowsEditing();
    [DllImport("__Internal")]
    private static extern void _iosSaveImageToPhotosAlbum(string readAddr);

    /// <summary>
    /// 打开照片
    /// </summary>
    /// <param name="allowsEditing"></param>
    public static void iosOpenPhotoLibrary(bool allowsEditing = false)
    {
        if (allowsEditing)
            _iosOpenPhotoLibrary_allowsEditing();
        else
            _iosOpenPhotoLibrary();
    }

    /// <summary>
    /// 打开相册
    /// </summary>
    /// <param name="allowsEditing"></param>
    public static void iosOpenPhotoAlbums(bool allowsEditing = false)
    {
        if (allowsEditing)
            _iosOpenPhotoAlbums_allowsEditing();
        else
            _iosOpenPhotoAlbums();
    }

    /// <summary>
    /// 打开相机
    /// </summary>
    /// <param name="allowsEditing"></param>
    public static void iosOpenCamera(bool allowsEditing = false)
    {
        if (allowsEditing)
            _iosOpenCamera_allowsEditing();
        else
            _iosOpenCamera();
    }

    /// <summary>
    /// 保存图片到相册
    /// </summary>
    /// <param name="readAddr"></param>
    public static void iosSaveImageToPhotosAlbum(string readAddr)
    {
        _iosSaveImageToPhotosAlbum(readAddr);
    }

    /// <summary>
    /// 将ios传过的string转成u3d中的texture
    /// </summary>
    /// <param name="base64"></param>
    /// <returns></returns>
    public static Texture2D Base64StringToTexture2D(string base64)
    {
        Texture2D tex = new Texture2D(4, 4, TextureFormat.ARGB32, false);
        try
        {
            //string temp = base64.Replace("+", "").Replace("\r\n","").Replace("/","");


            byte[] bytes = System.Convert.FromBase64String(base64);
            tex.LoadImage(bytes);
        }
        catch (System.Exception ex)
        {
            Debug.LogError(ex.Message);
        }
        return tex;
    }



    public System.Action<string> CallBack_PickImage_With_Base64;
    public System.Action<string> CallBack_ImageSavedToAlbum;

    /// <summary>
    /// 打开相册相机后的从ios回调到unity的方法
    /// </summary>
    /// <param name="base64">Base64.</param>
    void PickImageCallBack_Base64(string utf8)
    {
        Debug.Log("PickImageCallBack_Base64==" + utf8);
        byte[] bytesq = Encoding.UTF8.GetBytes(utf8);
        string base6 = Convert.ToBase64String(bytesq);
        IosImageStart(base6);
        Mytexture = GameObject.Find("Headimages").GetComponent<RawImage>();
        if (Mytexture)
        {
            Mytexture.texture = Base64StringToTexture2D(base6);
        }
    }

    /// <summary>
    /// 保存图片到相册后，从ios回调到unity的方法
    /// </summary>
    /// <param name="msg">Message.</param>
    void SaveImageToPhotosAlbumCallBack(string msg)
    {
        Debug.Log(" -- msg: " + msg);
        //IosImageStart(msg);
        PickImageCallBack_Base64(msg);
    }
#endif
}



